from django.shortcuts import render
from .models import Book, Author, BookInstance, Genre
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import permission_required


# Create your views here.
@permission_required('catalog.can_mark_returned')
@permission_required('catalog.can_edit')
def index(request):
    """
    View Function from home page of site.
    """
    # Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()
    # Available books (status = 'a')
    num_instance_available = BookInstance.objects.filter(
        status__exact='a').count()
    num_authors = Author.objects.all().count()
    num_visits = request.session.get('num_visits', 0)
    request.session['num_visits'] = num_visits + 1

    return render(
        request,
        'index.html',
        context={
            'num_books': num_books,
            'num_instances': num_instances,
            'num_instances_available': num_instance_available,
            'num_authors': num_authors,
            'num_visits': num_visits,
        },
    )


class BookListView(generic.ListView):
    model = Book
    context_object_name = 'book_list'  # your own name for the list as a template variable.
    queryset = Book.objects.all()[:5]  # get 5 books containing the title war
    template_name = 'book_list.html'  # Specify your own template name/location.

    # def get_queryset(self):
    #     """
    #     this method will override queryset field
    #     """
    #     return Book.bojects.filter(title__icontains='war')[:5]

    # def get_context_data(self, **kwargs):
    #     # Call the base implementation first to get the context.
    #     context = super(BookListView, self).get_context_data(**kwargs)
    #     # Create any data an add it to the context.
    #     context['some_data'] = 'This is just some data'
    #     return context


class BookDetailView(generic.DetailView):
    model = Book
    template_name = 'book_detail.html'


def book_detail_view(request, pk):
    try:
        book_id = Book.objects.get(pk=pk)
    except Book.DoesNoExist:
        raise Http404("Book does not exist")

    #book_id = get_object_or_404(Book, pk=pk)

    return render(request, 'book_detail.html', context={'book': book_id})


class AuthorListView(generic.ListView):
    model = Author
    template_name = 'author_list.html'
    context_object_name = 'author_list'

    def get_queryset(self):
        return Author.objects.all()[:5]

    def get_context_data(self, **kwargs):
        context = super(AuthorListView, self).get_context_data(**kwargs)
        context['my_idol'] = '吴军'
        return context


class AuthorDetailView(generic.DetailView):
    model = Author
    template_name = 'author_detail.html'


# TODO: 作者详情展示
def author_detail_view(request, pk):
    try:
        author_id = Author.objects.get(pk=pk)
        # book_id = Book.objects.get(pk=pk)
    except Book.DoesNoExist:
        raise Http404("Book does not exist")

    return render(
        request,
        'author_detail.html',
        context={
            # 'book': book_id,
            'author_id': author_id
        })


class LoanedBooksByUserListView(LoginRequiredMixin, generic.ListView):
    """
    Generic class-based view listing books on loan to current user.
    """
    model = BookInstance
    template_name = 'bookinstance_list_borrowed_user.html'
    paginate_by = 10

    def get_queryset(self):
        return BookInstance.objects.filter(borrower=self.request.user).filter(
            status__exact='o').order_by('due_back')
